import { onMounted, onUnmounted, ref } from 'vue'

import { throttle } from 'lodash'

export default function useScroll(elRef) {
  let el = window
  const isReachBottom = ref(false) //记录是否达到底部
  const clientHeight = ref(0)
  const scrollTop = ref(0)
  const scrollHeight = ref(0)
  // 当我们离开页面时，我们移除监听
  // 如果别的页面也进行类似的监听，会编写重复代码
  const scrollListenerHandler = throttle(() => {
    if (el === window) {
      clientHeight.value = document.documentElement.clientHeight //当前视图高度
      scrollTop.value = document.documentElement.scrollTop//当前滚动的位置
      scrollHeight.value = document.documentElement.scrollHeight//能滚动的区域
    } else {
      clientHeight.value = el.clientHeight //当前视图高度
      scrollTop.value = el.scrollTop//当前滚动的位置
      scrollHeight.value = el.scrollHeight//能滚动的区域
    }

    if (Math.ceil(clientHeight.value + scrollTop.value) >= Math.ceil(scrollHeight.value)) {
      console.log('到底了~')
      isReachBottom.value = true
    }
  }, 200)



  onMounted(() => {
    if (elRef) el = elRef.value
    el.addEventListener('scroll', scrollListenerHandler)
  })
  // 销毁周期
  onUnmounted(() => {
    window.removeEventListener('scroll', scrollListenerHandler)
  })

  return {
    isReachBottom,
    scrollTop,
    clientHeight,
    scrollHeight
  }
}